package com.xc.sbdemo.controller;


import com.xc.sbdemo.entity.Movie;
import com.xc.sbdemo.service.MovieService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api
@Controller
public class MovieController {
    @Autowired
    private MovieService movieService;

    @RequestMapping("/list")
    public String getList(Model model, @RequestParam(defaultValue = "1") Integer pageIndex){
        Integer pageSize=2;//一页几条记录
        int count = movieService.count();//总记录数
        int pageNum=count%pageSize==0?(count/pageSize):(count/pageSize)+1;//页数
        List<Movie> list = movieService.getList(pageIndex,pageSize);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("pageIndex",pageIndex);
        model.addAttribute("count",count);
        model.addAttribute("pageNum",pageNum);
        model.addAttribute("list",list);
        return "index";
    }
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "add";
    }

    @ResponseBody
    @PostMapping("/add")
    public String getAdd(Movie movie){
        System.out.println(movie.getRecommend());
        int result = movieService.add(movie);
        if (result>0){
            return "<script>alert('添加成功！');location.href='list'</script>";
        }
         return "<script>alert('添加失败！');location.href='add'</script>";
    }

    @ApiOperation("根据ID查看电影信息")
    @GetMapping("/view/{movieId}")
    public Movie view(@PathVariable(value = "id") @ApiParam("电影ID") Integer movieId, Model model){
        Movie movie = movieService.selectByMovieId(movieId);
        model.addAttribute("movie",movie);
        return movie;
    }

    @GetMapping("/upd")
    public String upd(Integer movieId, Model model){
        Movie movie = movieService.selectByMovieId(movieId);
        model.addAttribute("movie",movie);
        return "upd";
    }

    @ResponseBody
    @PostMapping("/modify")
    public String modify(Movie movie){
        int result = movieService.modify(movie);
        if (result>0){
            return "<script>alert('修改成功！');location.href='list'</script>";
        }
        return "<script>alert('修改失败！');location.href='upd'</script>";
    }

    @ResponseBody
    @DeleteMapping("/del/{movieId}")
    public String del(@PathVariable Integer movieId){
        int result=movieService.del(movieId);
        if (result>0){
            return "true";
        }
        return "false";
    }
    @ResponseBody
    @GetMapping("/selectByName")
    public String selectByName(String name){
        Movie movie = movieService.selectByMovieName(name);
        if (movie!=null){
            return "true";
        }
        return "false";
    }
}
